#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Shu Yang Wang
# Date: 2017/11/7

from django.conf import settings
from django.template import Library
from django.utils.safestring import mark_safe
import re

'''
根据用户session权限数据定制用户
'''
register = Library()

def process_menu_tree_data(request):
    '''
    根据Session中获取的菜单以及权限信息，结构化数据，生成特殊数据结构，如：
    [
        {id:1,caption:'菜单标题',parent_id:None,status:False,opened:False,child:[...]},
    ]
    :param request: 请求对象
    :return: 
    '''
    menu_permission_dict = request.session.get(settings.RBAC_MENU_PERMISSION_SESSION_KEY)
    if not menu_permission_dict:
        raise Exception('Session中未保存当前用户菜单以及权限信息，请登录后初始化权限信息！')

    """ session中获取菜单和权限信息 """
    all_menu_list = menu_permission_dict[settings.RBAC_MENU_KEY]
    menu_permission_list = menu_permission_dict[settings.RBAC_MENU_PERMISSION_KEY]

    all_menu_dict = {}
    for row in all_menu_list:
        row['opened'] = ''
        row['status'] = False
        row['child'] = []
        all_menu_dict[row['id']] = row

    """ 将权限信息挂靠在菜单上，并设置是否默认打开，以及默认显示 """
    for per in menu_permission_list:
        item = {'id': per['id'], 'caption': per['caption'],
                'url': per['url'], 'parent_id': per['menu_id'],
                'opened': False,
                'status': True}
        menu_id = item['parent_id']
        all_menu_dict[menu_id]['child'].append(item)

        # 将当前URL和权限正则进行匹配，用于指示是否默认打开菜单
        pattern = settings.RBAC_MATCH_PARTTERN.format(item['url'])
        if re.match(pattern, request.path_info):
            item['opened'] = 'active'

        if item['opened']:
            pid = menu_id
            while not all_menu_dict[pid]['opened']:
                all_menu_dict[pid]['opened'] = "active"
                pid = all_menu_dict[pid]['parent_id']
                if not pid:
                    break

        if item['status']:
            pid = menu_id
            while not all_menu_dict[pid]['status']:
                all_menu_dict[pid]['status'] = True
                pid = all_menu_dict[pid]['parent_id']
                if not pid:
                    break

    result = []
    for row in all_menu_list:
        pid = row['parent_id']
        if pid:
            all_menu_dict[pid]['child'].append(row)
        else:
            result.append(row)

    return result

def build_menu_tree_html(menu_list):
    '''
    递归生成菜单html
    :param menu_list: 结构化列表
    :return: 
    '''
    tp1 = """<li class="{0}">
            <a href={1}><i class="fa fa-circle-o"></i><span>{2}</a>
        </li>"""
    tp2 = """
    <li class="treeview {0}">
        <a ><i class="fa fa-link"></i>
            <span>{1}</span>
            <span class="pull-right-container">
                <i class="fa fa-angle-left pull-right"></i>
            </span>
        </a>
        <ul class="treeview-menu {0}">
            {2}
        </ul>
    </li>
    """
    html_str = ""
    for item in menu_list:
        # print(item)
        if not item['status']:
            continue
        if item.get('url'):
            html_str += tp1.format(item['opened'], item['url'], item['caption'])
        else:
            if item.get('child'):
                child = build_menu_tree_html(item.get('child'))
            else:
                child = ""
            html_str += tp2.format(item['opened'], item['caption'], child)
    return html_str



@register.inclusion_tag('bases/menu_tp.html')
def rbac_menu(request):
    '''
    返回母板
    :param request: 
    :return: 
    '''
    menu_tree_list = process_menu_tree_data(request)
    # print(menu_tree_list)
    html_str = build_menu_tree_html(menu_tree_list)
    return {"left_menu":mark_safe(html_str)}

